//main
import React, { useContext, useState, useRef } from "react";
import { connect } from "react-redux";
import { ThemeProvider, IconButton, Input } from "@material-ui/core";
import * as icons from "@material-ui/icons";
//data
import Context from "../../Context.js";
//styles
import { useStyles } from "./ChatSpace.jss";
//funcs
import { writeMessage } from "../../store/actions/chat";
import { sendMessage as sendMessageToWS } from "../../func/chatList/chat";
import Chat from "./Chat";

function ChatSpace(props) {
  const { theme, currentChat, WSConnectStatus } = useContext(Context);
  const classes = useStyles(theme);

  const [inputMessage, setInputMessage] = useState("");
  const [inputImage, setInputImage] = useState("");

  //img tag
  const uploadedImage = useRef(null);
  //form tag
  const imageUploader = useRef(null);
  const nullImageUploader = useRef(null);
  const handleImageUpload = (e) => {
    const [file] = e.target.files;
    if (file) {
      const reader = new FileReader();
      const { current } = uploadedImage;
      // current.file = file;
      reader.onload = (e) => {
        current.src = e.target.result;
        setInputImage(e.target.result);
      };
      reader.readAsDataURL(file);
    }
  };

  return (
    <ThemeProvider theme={theme}>
      <div className={classes.root}>
        <div className={classes.chatSpace}>
          <Chat />
          <div className={classes.inputPlace}>
            <Input
              className={classes.inputPlaceInput}
              value={inputMessage}
              onChange={(e) => setInputMessage(e.target.value)}
              onKeyPress={messageInputEnter}
              multiline
              variant="outlined"
              style={{ width: "100%" }}
              rowsMax="3"
            />
            <div className={classes.buttonsContainer}>
              <input
                type="file"
                onChange={handleImageUpload}
                ref={imageUploader}
                accept="image/jpeg,image/png"
                style={{ display: "none" }}
              />
              <input
                type="file"
                onChange={handleImageUpload}
                ref={nullImageUploader}
                accept="image/jpeg,image/png"
                style={{ display: "none" }}
              />
              <div className={classes.uploadedImageContainer}>
                <img className={classes.uploadedImage} ref={uploadedImage} />
              </div>
              <IconButton
                variant="contained"
                color="default"
                size="small"
                className={classes.attachButton}
                onClick={uploadImage}
              >
                <icons.Attachment />
              </IconButton>
              <IconButton
                variant="contained"
                color="default"
                size="small"
                className={classes.sendButton}
                onClick={sendMessage}
              >
                <icons.Send />
              </IconButton>
            </div>
          </div>
        </div>
        <div className={classes.onlinePanel}>
          <div className={classes.onlinePanelTitle}>Online:</div>
          <div className={classes.onlinePanelEntryBox}>
            {/* <div className={classes.onlinePanelEntry}>{onlineList}</div> */}
            <OnlineList />
          </div>
        </div>
      </div>
    </ThemeProvider>
  );

  function messageInputEnter(e) {
    switch (e.key) {
      case "Enter":
        if (e.ctrlKey) {
          setInputMessage(inputMessage + "\n");
        } else {
          e.preventDefault();
          sendMessage();
        }
        break;

      default:
        return undefined;
    }
  }

  async function sendMessage(e) {
    try {
      await sendMessageToWS(
        currentChat,
        props.chats[currentChat].key,
        inputImage,
        inputMessage,
        WSConnectStatus
      );
    } catch (err) {
      console.error(err);
    }
    setInputMessage("");
    imageUploader.current.files = nullImageUploader.current.files;
    uploadedImage.current.file = null;
    uploadedImage.current.src = "";
    setInputImage("");
  }

  function uploadImage() {
    imageUploader.current.click();
  }

  function OnlineList() {
    let list;
    try {
      list = props.chats[currentChat].onlineList;
      return list.map((key, index) => {
        return (
          <ThemeProvider theme={theme} key={index}>
            <div className={classes.onlinePanelEntry}>{list[index]}</div>
          </ThemeProvider>
        );
      });
    } catch (err) {
      // console.error(err);
      return <></>;
    }
  }
}

const mapStateToProps = (state) => {
  return {
    account: state.account.account,
    chats: state.chats,
  };
};

const mapDispathToProps = {
  writeMessage,
};

export default connect(mapStateToProps, mapDispathToProps)(ChatSpace);
